<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <!-- 添加按钮 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="showAddDialogClosed">添加分类</el-button>
        </el-col>
      </el-row>
      <!-- 表格 -->
      <tree-table
        :data="cateList"
        :columns="columns"
        :selection-type="false"
        :expand-type="false"
        show-index
        index-text="#"
        border
        :show-row-hover="false"
        class="TreeTable"
      >
        <!-- 是否有效模板 -->
        <template slot="isok" slot-scope="scope">
          <i class="el-icon-success" v-if="scope.row.cat_deleted===false" style="color:lightgreen"></i>
          <i class="el-icon-error" v-else style="color:red"></i>
        </template>
        <!-- 排序模板 -->
        <template slot="order" slot-scope="scope">
          <el-tag size="mini" v-if="scope.row.cat_level===0">一级</el-tag>
          <el-tag type="success" size="mini" v-else-if="scope.row.cat_level===1">二级</el-tag>
          <el-tag type="warning" size="mini" v-else>三级</el-tag>
        </template>

        <!-- 操作模板 -->
        <template slot="opt" slot-scope="scope">
          <el-button type="primary" icon="el-icon-edit" size="mini" @click="editClick(scope.row)">编辑</el-button>
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="mini"
            @click="deleteClick(scope.row.cat_id)"
          >删除</el-button>
        </template>
      </tree-table>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>

    <!-- 添加对话框 -->
    <el-dialog title="添加分类" :visible.sync="addDialogVisible" width="50%" @close="addDialogClosed">
      <!-- 主题内容区域 -->
      <el-form
        :model="addCateForm"
        :rules="addCateFormRules"
        ref="addCateFormRef"
        label-width="100px"
      >
        <el-form-item label="分类名称：" prop="cat_name">
          <el-input v-model="addCateForm.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="父级名称：">
          <el-cascader
            v-model="selectKeys"
            :options="parentCateList"
            :props="{checkStrictly:true, expandTrigger: 'hover', value: 'cat_id',
        label: 'cat_name',
        children: 'children'}"
            @change="parentCateListChange"
            clearable
          ></el-cascader>
        </el-form-item>
      </el-form>
      <!-- 底部按钮区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addCate">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑对话框 -->
    <el-dialog title="编辑分类" :visible.sync="editDialogVisible" width="50%" @close="editDialogClosed">
      <!-- 主题内容区域 -->
      <el-form
        :model="editCateForm"
        :rules="editCateFormRules"
        ref="editCateFormRef"
        label-width="100px"
      >
        <el-form-item label="分类名称：" prop="cat_name">
          <el-input v-model="editCateForm.cat_name"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部按钮区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editCate">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      //查询条件
      queryInfo: {
        type: 3,
        pagenum: 1,
        pagesize: 5,
      },
      //商品分类列表
      cateList: [],
      //总数据条数
      total: 0,
      //为table指定列定义
      columns: [
        {
          label: "分类名称",
          prop: "cat_name",
        },
        {
          label: "是否有效",
          type: "template",
          template: "isok",
        },
        {
          label: "排序",
          type: "template",
          template: "order",
        },
        {
          label: "操作",
          type: "template",
          template: "opt",
        },
      ],
      //显示添加分类对话框
      addDialogVisible: false,
      //显示编辑分类对话框
      editDialogVisible: false,
      //添加分类数据保存
      addCateForm: {
        cat_name: "",
        //   父级分类的id
        cat_id: 0,
        // 分类等级默认为一级分类
        cat_level: 0,
      },
      //编辑分类数据保存:
      editCateForm: {
        cat_id: "",
        cat_name: "",
      },
      //添加分类表单验证规则的对象
      addCateFormRules: {
        cat_name: [
          { required: true, message: "请输入分类名称", trigger: "blur" },
        ],
      },
      //编辑分类表单验证规则的对象
      editCateFormRules: {
        cat_name: [
          { required: true, message: "请输入分类名称", trigger: "blur" },
        ],
      },
      //父级分类的列表
      parentCateList: [],
      //级联选择器的配置对象
      cateProps: {
        value: "cat_id",
        label: "cat_name",
        children: "children",
      },
      //保存选中的id分类的id数组
      selectKeys: [],
    };
  },
  created() {
    this.getCateList();
  },
  methods: {
    //获取分类列表数据
    async getCateList() {
      const { data: res } = await this.$http.get("categories", {
        params: this.queryInfo,
      });
      if (res.meta.status !== 200)
        return this.$message.error("获取商品分类失败！");
      //   console.log(res);
      //   数据列表赋值
      this.cateList = res.data.result;
      //   总数据条数赋值
      this.total = res.data.total;
    },
    //监听pagesize的改变
    handleSizeChange(newsize) {
      this.queryInfo.pagesize = newsize;
      this.getCateList();
    },
    //监听pagenum
    handleCurrentChange(newpage) {
      this.queryInfo.pagenum = newpage;
      this.getCateList();
    },
    //当添加分类对话框关闭后
    addDialogClosed() {
      this.$refs.addCateFormRef.resetFields();
      this.selectKeys = [];
      this.addCateForm.cat_level = 0;
      this.addCateForm.cat_id = 0;
    },
    //点击添加分类按钮
    showAddDialogClosed() {
      // 获取父级分类列表
      this.getParentCateList();
      this.addDialogVisible = true;
      //   console.log("jsjsi");
    },
    //获取前两级的父级分类
    async getParentCateList() {
      const { data: res } = await this.$http.get("categories", {
        params: { type: 2 },
      });
      if (res.meta.status !== 200)
        return this.$message.error("获取父级分类失败");
      // console.log(res.data);
      this.parentCateList = res.data;
    },
    //选择项发生改变
    parentCateListChange() {
      if (this.selectKeys.length > 0) {
        // this.addCateForm.
        this.addCateForm.cat_id = this.selectKeys[this.selectKeys.length - 1];
        this.addCateForm.cat_level = this.selectKeys.length;
        return;
      } else {
        this.addCateForm.cat_id = 0;
        this.addCateForm.cat_level = 0;
      }
    },
    // 点击确认提交
    addCate() {
      // console.log(this.addCateForm)
      this.$refs.addCateFormRef.validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.$http.post("categories", {
          cat_pid: this.addCateForm.cat_id,
          cat_name: this.addCateForm.cat_name,
          cat_level: this.addCateForm.cat_level,
        });
        if (res.meta.status !== 201)
          return this.$message.error("添加分类失败！");
        this.$message.success("添加分类成功");
        this.getCateList();
        this.addDialogVisible = false;
      });
    },
    //点击编辑按钮显示对话框
    async editClick(cate) {
      // console.log(cate);
      // 拿到编辑分类的名称
      const { data: res } = await this.$http.get("categories/" + cate.cat_id);
      if (res.meta.status !== 200) return this.$message.error("查询分类失败");
      this.editCateForm.cat_name = res.data.cat_name;
      this.editCateForm.cat_id = res.data.cat_id;
      this.editDialogVisible = true;
    },
    // 编辑对话框关闭后
    editDialogClosed() {
      this.$refs.editCateFormRef.resetFields();
      this.editCateForm.cat_id = "";
      this.editCateForm.cat_name = "";
      console.log(this.editCateForm);
    },
    //点击确认提交编辑
    editCate() {
      this.$refs.editCateFormRef.validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.$http.put(
          "categories/" + this.editCateForm.cat_id,
          { cat_name: this.editCateForm.cat_name }
        );
        if (res.meta.status !== 200)
          return this.$message.error("编辑分类失败！");
        this.$message.success("编辑分类成功");
        this.getCateList();
        this.editDialogVisible = false;
      });
    },
    //根据id删除分类
    async deleteClick(id) {
      // console.log(id)
      const confirmResult = await this.$confirm(
        "此操作将永久删除该分类, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => {
        return err;
      });
      if (confirmResult !== "confirm") {
        return this.$message.info("已经取消删除");
      }
      const { data: res } = await this.$http.delete("categories/" + id);
      if (res.meta.status !== 200) {
        // 删除失败
        return this.$message.error("删除分类失败");
      }
      this.$message.success("删除分类成功");
      this.getCateList();
    },
  },
};
</script>
<style lang="less" scoped>
.TreeTable {
  margin-top: 15px;
}
</style>